import L from 'leaflet';
import {zoom} from "leaflet/src/control/Control.Zoom";

//地图瓦片加载地址
const mapUrl = {
    ArcGIS: "http://services.arcgisonline.com/ArcGIS/services/World_Imagery/MapServer?mapname=Layers&layer=_alllayers&level={z}&row={y}&column={x}&format=PNG", // arcgis
    TianYu: "http://gis.tianyujingwei.com:9099/satellitemap/Chinanooffset2/Chinanooffset3/瓦片_谷歌/{z}/{x}/{y}.jpg", // 天宇地图
    TianDi: "http://t4.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=e4d4fa6c281d4bc106e6babd0afa2fbf", // 天地图
    TianDi1: "http://t4.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=e4d4fa6c281d4bc106e6babd0afa2fbf", // 天地图
    GaoDe:  "https://wprd01.is.autonavi.com/appmaptile?style=6&lang=zh_cn&scl=2&x={x}&y={y}&z={z}", // 高德地图
}

export class LeafLetMap {

    //构造函数
    constructor(dom,mapSource = mapUrl.ArcGIS){
        this.init(dom,mapSource);
    }

    //地图初始化
    init(dom,mapSource){
        this.map = L.map(dom,{
            zoomControl: false,
            attributionControl: false,
            maxZoom:"23",
            minZoom:"4",
            rotate: true,
            editable: true,
            closePopupOnClick: false
        }).setView([40.065174,116.34674], 4);
        L.tileLayer(mapSource, {
            minZoom: 4,
            maxZoom: 23
        }).addTo(this.map);
        L.tileLayer(mapUrl.TianDi1, {
            minZoom: 4,
            maxZoom: 23
        }).addTo(this.map);
        this.map.on("zoomend", function (e) {
            let zoom = e.target.getZoom();
        });
        this.map.on("click", function (e) {
            let point = e.latlng;
        });
        return this;
    }

    //移除图层
    removeMap(){
        this.map.remove();
    }

    //移除图层
    removeLayer(layer){
        this.map.removeLayer(layer);
    }

    //渲染正射影像
    renderDomImage(url){
        let tileLayer = L.tileLayer(url+'{z}/{x}/{y}.png', {
            minZoom: 4,
            maxZoom: 23
        });
        this.map.addLayer(tileLayer);
        return tileLayer;
    }

    /**
     * 渲染多边形
     * @param points 多边形点
     * @param options 多边形样式参数
     * @param params 多边形参数
     * @return {*}
     */
    renderPolygon(points,options,params){
        let line = L.polygon(points, options);
        this.map.addLayer(line);
        this.map.fitBounds(line.getBounds());
        return  line;
    }

    //渲染线
    renderPolyline(points,options){
        let line = L.polyline(points, options);
        this.map.addLayer(line);
        return  line;
    }

    //渲染航线
    renderInspectLine(points,options){
        let line = this.renderPolyline(points,options)
        this.map.fitBounds(line.getBounds());
        return line;
    }

    addMessagePopup(point,messageType){
        let iconClassName = 'icon-map-marker';
        let position = [point['lat'],point['lng']];
        let popup = L.popup({
            closeButton:false,
            autoClose:false,
            autoPan:false
        }).setLatLng(position)
            .setContent(`<div class="iconfont ${iconClassName}" data-uavId-${point.uavId}="${point.uavId}" style="font-size: 30px !important;color: #1afa29;position: absolute;left: 11px;top: -26px;cursor: pointer;">
            </div>`).openOn(this.map);
        this.map.addLayer(popup);
        this.setMapCenter(point['lng'],point['lat'])
        return popup;
    }

    //设置地图中心点
    setMapZoom(zoom){
        this.map.setZoom(zoom);
    }

    //设置地图中心点[40.065642,116.346847]
    setMapCenter(lng,lat){
        this.map.setView([lat,lng],this.map.getZoom());
    }

    //设置地图中心点
    setMapCenterAndZoom(lng,lat,zoom = this.map.getZoom()){
        this.map.setView([lat,lng],zoom);
    }

    getMapPoint(){
        console.log()
    }

    addPileCardClusterMarker(dataList){
        let markers = L.markerClusterGroup();
        let options = L.icon({  //编辑聚合点icon
            iconUrl: 'image/zhuangpai.png',
            iconSize: [36, 36],
            iconAnchor: [18, 36],
            popupAnchor: [0, -13],
        });
        for (let item of dataList) {
            let marker = L.marker(new L.LatLng(item.lat, item.lng), {
                title: item[''],
                icon: options
            });
            marker.on('click',  function () {
                let pileCardNumber = item['systemStakeNumber'];
                try {
                    if (pileCardNumber !== undefined){
                        bridge['setPileCard'](pileCardNumber);
                    }
                }catch (e) {
                    console.error("QT方法需在QT环境下调用...")
                }
            });
            let popEl = document.createElement("div");
            popEl.className = 'r-n-c-c'
            popEl.style.background = 'rgb(174, 125, 25)';
            let popElInner = document.createElement("div");
            popElInner.style.margin = '2px';
            popElInner.style.borderRadius = '2px';
            popElInner.className = 'r-n-c-c'
            popElInner.style.background = 'rgb(234, 169, 40)';
            let html = `<div style="padding: 10px;width: 100%;height: 100%;">
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">桩号: &nbsp;&nbsp; ${item['systemStakeNumber']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">类型: &nbsp;&nbsp; ${item['pileCardTypeName']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">经度: &nbsp;&nbsp; ${item['lng']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">纬度: &nbsp;&nbsp; ${item['lat']}</div>`;
            if (item['sceneImage'] !== undefined){
                html+= `<div style="font-size: 12px;line-height: 20px;color: #FFFFFF;text-align: left;padding-top: 5px">
                            <img src="${item['sceneImage']}" width="180" alt="图片加载错误">
                        </div>`;
            }
            html+=`</div>`;
            popElInner.innerHTML = html;
            popEl.appendChild(popElInner)
            marker.bindPopup(popEl, {
                minWidth: 100,
                maxWidth: 270,
                offset: [0, -22],
                closeOnClick: true,
                closeButton: false,
                autoClose: false,
                closeOnEscapeKey: false,
                autoPan: false,
                className: 'uav_panel'
            });
            markers.addLayer(marker);
        }
        this.map.addLayer(markers);
        return markers;
    }

    /**
     * 添加实时无人机图标
     * @param telemetry 遥测数据
     * @param callback 回调函数
     * @return popup
     */
    addUavPopup(telemetry,istTransform,callback){
        let iconClassName = '';
        if (telemetry['source'] === "御空"){
            //多旋翼
            iconClassName = 'icon-wurenji3';
        }else if (telemetry['source'] === "云平台"){
            //固定翼
            iconClassName = 'icon-gudingyi';
        }
        console.log(iconClassName)
        let position = [telemetry['latitude'],telemetry['longitude']];
        let deg = telemetry['yaw']+`deg`;
        let popup = L.popup({
            closeButton:false,
            autoClose:false,
            autoPan:false
        }).setLatLng(position)
            .setContent(`<div class="iconfont ${iconClassName}" data-uavId-${telemetry.uavId}="${telemetry.uavId}" style="font-size: 30px !important;color: #1afa29;position: absolute;left: 11px;top: -26px;cursor: pointer;transform:rotate(${deg});">
            </div>`).openOn(this.map);
        let popupElement = popup.getElement();
        popupElement.onclick = callback;
        this.map.addLayer(popup);
        return popup;
    }

    /**
     * 添加险情图标 [40.065642,116.346847]
     * @param danger 险情数据
     * @param callback 回调函数
     * @return popup
     */
    addDangerPopup(danger,callback){
        let position = [danger['lat'],danger['lng']];
        let popup = L.popup({
            closeButton:false,
            autoClose:false,
            autoPan:false
        }).setLatLng(position)
            .setContent(`<div class="iconfont" data-icon-danger-id="${danger.id}" style="font-size: 40px !important;color: #ff6700;position: absolute;left: 12px;top: -50px;cursor: pointer;">
                <img src="image/danger-level-${danger.dangerLevelId}.png" alt="${danger.typeName}" width="28" height="28">
            </div>`).openOn(this.map);
        let popupElement = popup.getElement();
        popupElement.onclick = callback;
        this.map.addLayer(popup);
        this.setMapCenterAndZoom(danger['lng'],danger['lat'],this.map.getZoom());
        return popup;
    }

    /**
     * 添加桩牌图标
     * @param pileCard 桩牌数据
     * @param callback 回调函数
     * @return popup
     */
    addPileCardPopup(pileCard,callback){
        let position = [pileCard['lat'],pileCard['lng']];
        let popup = L.popup({
            closeButton:false,
            autoClose:false,
            autoPan:false
        }).setLatLng(position)
            .setContent(`<div class="iconfont" data-pile-card="${pileCard['id']}" data-pile-card-number="${pileCard['systemStakeNumber']}"  style="font-size: 40px !important;color: #ff6700;position: absolute;left: 8px;top: -48px;cursor: pointer;">
                <img src="image/zhuangpai.png" alt="${pileCard['systemStakeNumber']}" width="36" height="36">
            </div>`).openOn(this.map);
        let popupElement = popup.getElement();
        popupElement.onclick = callback;
        this.map.addLayer(popup);
        return popup;
    }

    /**
     * 添加设施图标
     * @param generalFacilities 设施数据
     * @param callback 回调函数
     * @return popup
     */
    addValueChestPopup(generalFacilities,callback){
        let position = [generalFacilities['lat'],generalFacilities['lng']];
        let marker = L.marker(position,{icon:L.icon({
                iconUrl: 'image/fashi.png',
                iconSize: [36, 36],
                iconAnchor: [22, 38],
                popupAnchor: [-3, -76],
            })});

        if (generalFacilities['generalFacilitiesTypeName'] !== undefined){
            let popEl = document.createElement("div");
            popEl.className = 'r-n-c-c'
            popEl.style.background = 'rgb(174, 125, 25)';
            let popElInner = document.createElement("div");
            popElInner.style.margin = '2px';
            popElInner.style.borderRadius = '2px';
            popElInner.className = 'r-n-c-c'
            popElInner.style.background = 'rgb(234, 169, 40)';
            let html = `<div style="padding: 10px;width: 100%;height: 100%;">
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">编号: &nbsp;&nbsp; ${generalFacilities['number']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">类型: &nbsp;&nbsp; ${generalFacilities['generalFacilitiesTypeName']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">经度: &nbsp;&nbsp; ${generalFacilities['lng']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">纬度: &nbsp;&nbsp; ${generalFacilities['lat']}</div>`;
            if (generalFacilities['sceneImage'] !== undefined){
                html+= `<div style="font-size: 12px;line-height: 20px;color: #FFFFFF;text-align: left;padding-top: 5px">
                            <img src="${generalFacilities['sceneImage']}" width="180" alt="图片加载错误">
                        </div>`;
            }
            html+=`</div>`;
            popElInner.innerHTML = html;
            popEl.appendChild(popElInner)
            marker.bindPopup(popEl,{
                minWidth: 100,
                maxWidth: 300,
                offset:[0,38],
                closeOnClick: true,
                autoClose: false,
                closeOnEscapeKey: false,
                autoPan: false
            }).openPopup();
        }
        this.map.addLayer(marker);
        return marker;
    }

    /**
     * 添加施工单位图标
     * @param constructionUnits 施工单位数据
     * @param callback 回调函数
     * @return popup
     */
    addConstructionUnitsPopup(constructionUnits,callback){
        let position = [constructionUnits['lat'],constructionUnits['lng']];
        // let popup = L.popup({
        //     closeButton:false,
        //     autoClose:false,
        //     autoPan:false
        // }).setLatLng(position)
        //     .setContent(`<div class="iconfont" data-constructionUnits="${constructionUnits.id}" style="font-size: 40px !important;color: #ff6700;position: absolute;left: 8px;top: -48px;cursor: pointer;">
        //         <img src="image/shigong.png" alt="${constructionUnits.id}" width="36" height="36">
        //     </div>`).openOn(this.map);
        // let popupElement = popup.getElement();
        // popupElement.onclick = callback;
        //this.map.addLayer(popup);
        let marker = L.marker(position,{icon:L.icon({
                iconUrl: 'image/shigong.png',
                iconSize: [36, 36],
                iconAnchor: [22, 38],
                popupAnchor: [-3, -76],
            })});

        if (constructionUnits['constructionTypeName'] !== undefined){
            let popEl = document.createElement("div");
            popEl.className = 'r-n-c-c'
            popEl.style.background = 'rgb(174, 125, 25)';
            let popElInner = document.createElement("div");
            popElInner.style.margin = '2px';
            popElInner.style.borderRadius = '2px';
            popElInner.className = 'r-n-c-c'
            popElInner.style.background = 'rgb(234, 169, 40)';
            let html = `<div style="padding: 10px;width: 100%;height: 100%;">
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">编号: &nbsp;&nbsp; ${constructionUnits['number']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">类型: &nbsp;&nbsp; ${constructionUnits['constructionTypeName']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">经度: &nbsp;&nbsp; ${constructionUnits['lng']}</div>
                <div style="font-size: 12px;line-height: 20px;color: #000;text-align: left">纬度: &nbsp;&nbsp; ${constructionUnits['lat']}</div>`;
            if (constructionUnits['sceneImage'] !== undefined){
                html+= `<div style="font-size: 12px;line-height: 20px;color: #FFFFFF;text-align: left;padding-top: 5px">
                            <img src="${constructionUnits['sceneImage']}" width="180" alt="图片加载错误">
                        </div>`;
            }
            html+=`</div>`;
            popElInner.innerHTML = html;
            popEl.appendChild(popElInner)
            marker.bindPopup(popEl,{
                minWidth: 100,
                maxWidth: 300,
                offset:[0,38],
                closeOnClick: true,
                autoClose: false,
                closeOnEscapeKey: false,
                autoPan: false
            }).openPopup();
        }

        this.map.addLayer(marker);
        return marker;

    }

    /**
     * 添加高后果区区域
     * @param highConsequenceAreas 施工单位数据
     * @param options 参数
     * @return popup
     */
    addHighConsequenceAreasPolygon(highConsequenceAreas,options){
        let points = highConsequenceAreas['polygonPointList'];
        let latLngS = [];
        for (let point of points) {
            latLngS.push([point['lat'],point['lng']]);
        }
        return this.renderPolygon(latLngS,options,highConsequenceAreas);
    }
}